<template>
    <div>
        <div class="collapse-content" style="margin-top: 10px;">
            <div class="collapse-card"  ref="table-wrapper">
                <div class="collapse-card-header" @click="toggleBox(1)">
                    <div class="collapse-title">
                        <div>
                            <i class="iconfont title-icon">&#xea44;</i>
                            率定信息
                            <el-popover
                                placement="right"
                                width="340"
                                trigger="hover">
                                <div>
                                    <div class="formulaTitle">使用公式</div>
                                    <div class="formulaWrapper">
                                        <p v-for="(item,index) in formulaList" :key="index" class="formula">{{ item }}</p>
                                    </div>
                                </div>
                            <i class="header-icon el-icon-info"  slot="reference" v-show="formulaList.length > 0"></i>
                            </el-popover>
                        </div>
                        <div>
                            <el-tooltip class="item" effect="dark" content="无新增权限" placement="top-start" :disabled="showRoleAdd == 1">
                                    <el-button type="primary" size="mini" icon="el-icon-plus"  @click.stop="handleAddPointMore()" :disabled="showRoleAdd == 0">新增</el-button>
                            </el-tooltip>
                            
        <!-- <el-link type="text" size="medium" icon="el-icon-setting" @click.stop="handleAddPointMore" style="margin-right: 20px;" v-if="showRoleAdd">增加</el-link> -->
                        </div>
                    </div>
                
                    <div class="chart-actions">
                        <el-tooltip effect="dark" content="展开/折叠表格" placement="top">
                        <i 
                            class="el-icon-arrow-right expand-icon" 
                            :class="{ 'expanded': activeNames.includes(1) }"
                        ></i>
                        </el-tooltip>
                    </div>
                </div>
                <transition name="collapse">
                    <div class="right-wrapper-top" v-show="isTableExpanded">
                        <calibrationTable :maxHeight="collapseTable" :tableData="pointDataList" :titleList="pointTitle" @edit="handleAddPoint" @del="handleDelPointList" :showRoleEdit="showRoleEdit" :showRoleDel="showRoleDel"></calibrationTable>
                    </div>
                </transition>
            </div>
            <div class="collapse-card" style="margin-top:10px">
                <div class="collapse-card-header" @click="toggleBox(2)">
                    <div class="collapse-title">
                        <div> <i class="iconfont title-icon">&#xe658;</i>关联POINT</div>
                    </div>
                
                    <div class="chart-actions">
                        <el-tooltip effect="dark" content="展开/折叠图表" placement="top">
                        <i 
                            class="el-icon-arrow-right expand-icon" 
                            :class="{ 'expanded': activeNames.includes(2) }"
                        ></i>
                        </el-tooltip>
                    </div>
                </div>
                <transition name="collapse">
                    <div class="right-wrapper-bot" v-show="isPointExpanded">
                        <pointConcatDialog :pointList="pointList" :height="collapseTable2" @update="onPointVales" :showRoleEdit="showRoleEdit"/>
                    </div>
                </transition>
            </div>
        </div>

        <calibrationAddDialog :pointFormLabel="pointFormLabel" :visible.sync="pointListDialogVisible" :pointForm="pointForm" :formulaList="formulaList" :pointNameList="pointNameList"  @handleSavePoint="handleSavePoint"/>


        <el-dialog title="批量增加"  :visible.sync="appendDatasDialogVisible"
        v-dialogDrag :before-close="handleCancelDialogTable"
        width="90%">
            <div v-if="formulaList.length > 0" >
                <div class="formulaTitle">使用公式</div>
                <div class="formulaWrapper">
                    <div v-for="(item,index) in formulaList" :key="index" class="formula">{{ item }}</div>
                </div>
            </div>
            <ve-table
                fixed-header
                max-height="calc(100vh - 450px)"
                :columns="pointColumns"
                :table-data="pointDialogDataList"
                rowKeyFieldName="rowKey"
                :rowStyleOption="rowStyleOption"
                :clipboard-option="clipboardOptionDialog"
                :cell-autofill-option="cellAutofillOptionDialog"
                :edit-option="editOptionDialog"
                :contextmenu-body-option="contextmenuBodyOption"
                border-y
                border-x
                ref="tableRefDialog"
                style="margin-top:10px"
            />
            <div class="dialog-footer">
                <el-button  @click="handleCancelDialogTable" icon="el-icon-circle-close" size="small" class="cancel-btn">取消</el-button>
                <el-button type="primary"  @click="handleSaveDialogTable" size="small" icon="el-icon-circle-check" class="confirm-btn">保存数据</el-button>
            </div>
        </el-dialog>


        <el-dialog  :visible.sync="addRowDialogVisible" width="360px" v-dialogDrag>
            <div>
                追加行数：<el-input-number v-model="num" :min="2" label="请输入" size="small"></el-input-number>
                <el-alert style="margin-top:10px"
                    title="数字越大，系统加载越慢，请按需输入"
                    type="warning" :closable="false">
                </el-alert>
            </div>
            <div style="text-align: right; margin-top: 10px">
                <el-button size="small" @click="addRowDialogVisible = false">取消</el-button>
                <el-button type="primary" size="small" @click="handleAddRowClick">确定</el-button>
            </div>
        </el-dialog>


    </div>
</template>

<script>
import {PointQueryById,PointQueryPoint,GetFormulaByModeId,getPointValves,PointQueryByIdAdd,PointQueryByIdEdit,PointQueryByIdDel,QueryTitleByTreeID,SetAllParamsByTreeID} from '@/api/https'
import noData from '../../base/noData.vue'
import treeMenu from '../../base/treeMenu.vue'
import calibrationAddDialog from '@/components/page/information/calibrationAddDialog.vue'
import calibrationTable from '@/components/page/information/calibrationTable.vue'
import pointConcatDialog from '@/components/page/information/pointConcatDialog.vue'
import DateUtils from "@/utils/dateUtils";
export default ({
    components:{noData,treeMenu,calibrationAddDialog,calibrationTable,pointConcatDialog},
    props:{
        stationId:{
            type:[String,Number],
            default:''
        },
        treeId:{
            type:Number,
            default:0
        },
        menuSelModel:{
            type:String,
            default:''
        },
        treeNodeId:{
            type:Number,
            default:0
        },
        showRoleAdd:{
            type:Number,
            default:0
        },
        showRoleEdit:{
            type:Number,
            default:0
        },
        showRoleDel:{
            type:Number,
            default:0
        }
    },
     watch:{
        'stationId':{
            handler(newVal,oldVal){
                this.clearData()
                this.onPointQuery()
                this.onPointVales()
            }
        },
        'treeId':{
            handler(newVal,oldVal){
                this.clearData()
                this.onPointQuery()
                this.onPointVales()
            }
        },
        'menuSelModel':{
            handler(newVal,oldVal){
                this.clearData()
            }
        }
    },
    mounted(){
        this.onPointQuery()
        this.onPointVales()
    },
    computed: {
        isSingleExpanded() {
            return this.activeNames.length === 1
        },
        pointColumns(){
            let pointColumns = []
            pointColumns.push({
                field: "index",
                key: "index",
                operationColumn: true,
                title: "序号",
                width: 50,
                fixed: "left",
                renderBodyCell: ({ row, column, rowIndex }, h) => {
                    return ++rowIndex;
                },
            },{
                field: "pointName",
                key: "pointName",
                title: "测点名称",
                edit:false,
                renderBodyCell: ({ row, column, rowIndex }, h) => {
                        return (
                            <div>
                                <el-select
                                size="small"
                                style="width:100px"
                                value={row["pointName"]}
                                on-input={(val) => {
                                    row["pointName"] = val;
                                    this.pointNameList.forEach(item=>{
                                    if(item.pointName == val){
                                        row["codE_ID"] = item.codE_ID;
                                    }
                                    })
                                }}
                                placeholder="请选择">   
                                {
                                this.pointNameList.map(item=>{
                                    return  <el-option label={item.pointName} value={item.pointName}></el-option>
                                })
                                }
                            </el-select>    
                            </div>
                        );
                    },
                })
                if(this.pointDialogDataList.length > 0){
                    this.pointTitle.forEach(item=>{
                        pointColumns.push({
                            title: item.paramName,
                            field:item.paramName,
                            key:item.paramName,
                            edit:true
                        })
                    })
                    pointColumns.push({
                        title: '时间',
                        field:'dt',
                        key:'dt',
                        edit:false,
                        renderBodyCell: ({ row, column, rowIndex }, h) => {
                            return (
                                <div>
                                    <el-date-picker
                                    size="small"
                                    style="width:200px"
                                    value={row["dt"]}
                                    on-input={(val) => {
                                    row["dt"] = val;
                                    }}
                                    type="date"
                                    format="yyyy 年 MM 月 dd 日"
                                    value-format="yyyy/MM/dd" 
                                    placeholder="选择日期">
                                    </el-date-picker>
                                </div>
                            );
                        },
                    })                                  
                }else{
                    pointColumns = []
                }
            return pointColumns
        },
        isTableExpanded() {
            return this.activeNames.includes(1);
        },
        isPointExpanded() {
            return this.activeNames.includes(2);
        }
    },
    data() {
        return {
            pageIndex:1,
            totalPage:1,
            pointDataList:[],
            pointFormLabel:[],
            pointTitle:[],
            pointNameList:[],
            activeNames:[1,2],
            collapseTable:`calc(100vh - 542px)`,
            collapseTable2: `calc(100vh - 700px)`,
            pointList:[],
            formulaList:[],
            pointListDialogVisible:false,
            pointForm:{},
            pointDialogEdit:false,
            Old_DT:'',
            appendDatasDialogVisible:false,
            pointDialogDataList:[],
            dialogParams:[],
            rowStyleOption: {
                clickHighlight: false,
                hoverHighlight: true,
            },
            clipboardOptionDialog:{
                copy: true,
                paste: true,
                cut: true,
                delete: true,
                beforePaste: ({ data, selectionRangeIndexes, selectionRangeKeys }) => {
                    if(selectionRangeKeys.startColKey == 'pointName' || selectionRangeKeys.endColKey == 'pointName'){
                        this.$message.error('测点名称不能粘贴！')
                        return false
                    }
                },
            },
            cellAutofillOptionDialog:{
                directionX: false,
                directionY: true,
                beforeAutofill:(data)=>{
                    const keys = Object.keys(data.sourceSelectionData[0])
                    if(keys[0] == 'pointName' || keys[1] == 'pointName'){
                        return false
                    }
                }
            },
            editOptionDialog:{
                afterCellValueChange: ({ row, column, changeValue }) => {  
                    
                },
            },
            addRowDialogVisible:false,
            num:2,
            contextmenuBodyOption: {
                contextmenus: [
                    {
                        type: "CUT",
                    },
                    {
                        type: "COPY",
                    },
                    {
                        type: "SEPARATOR",
                    },
                    {
                        type: "INSERT_ROW_ABOVE",
                    },
                    {
                        type: "INSERT_ROW_BELOW",
                    },
                    {
                        type:'addRowMore',
                        label:'追加多行'
                    },
                    {
                        type: "SEPARATOR",
                    },
                    {
                        type: "REMOVE_ROW",
                    },
                    {
                        type: "EMPTY_ROW",
                    },
                    {
                        type: "EMPTY_CELL",
                    },
                ],
                afterMenuClick: ({ type, selectionRangeKeys, selectionRangeIndexes })=> {
                    if(type == 'addRowMore'){
                        this.addRowDialogVisible = true
                    }
                },
            },
        }
    },
    beforeDestroy() {
        this.pointDialogDataList = [];
        this.pointDataList = [];
        this.pointNameList = [];
    },
    methods:{
        toggleBox(num) {
            const index = this.activeNames.indexOf(num);
            if (index > -1) {
                this.activeNames.splice(index, 1);
            } else {
                this.activeNames.push(num);
            }
            this.adjustTableHeight();
        },
        adjustTableHeight() {
            const hasTable = this.isTableExpanded;
            const hasPoint = this.isPointExpanded;
            
            if (hasTable && !hasPoint) {
                this.collapseTable = `calc(100vh - 310px)`
            } else if (!hasTable && hasPoint) {
                this.collapseTable2 = `calc(100vh - 310px)`
            } else {
                this.collapseTable = `calc(100vh - 542px)`,
                this.collapseTable2 = `calc(100vh - 700px)`
            }
        },
        clearData(){
            this.pageIndex = 1
            this.totalPage = 1
            this.pointDataList = []
            this.pointFormLabel = []
            this.pointTitle = []
            this.pointNameList = []
        },
        onPointQuery(){
            if(this.treeId){
                const _data = {
                    treeId:this.treeId,
                    statioN_ID:this.stationId,
                    treeStyle:this.menuSelModel,
                    pageIndex:this.pageIndex,
                    pageSize:50
                }
                PointQueryById(_data).then(res=>{
                    if(res.isSuccess){
                        if(res.data && res.data.data && res.data.data.length > 0){
                            // 表格内容
                            const _d = res.data
                            const tableList = []
                            _d.data.forEach((item,index)=>{
                                const _obj = {
                                    codE_ID:item.codE_ID,
                                    dt:item.dt,
                                    pointName:item.pointName,
                                    prefix:item.prefix,
                                    rowKey:index++
                                }
                                if(item.params && item.params.length > 0){
                                    item.params.forEach(subItem=>{
                                        _obj[subItem.param] = subItem.value
                                    })
                                }
                                tableList.push(_obj)
                            })
                            this.pointDataList = [...tableList]

                            if(_d.title.params && _d.title.params.length > 0){
                                const list = []
                                 _d.title.params.forEach(item=>{
                                    // 弹窗的动态表头
                                    const _obj = {}
                                    _obj.key = item.param
                                    _obj.value = item.paramName
                                    list.push(_obj)
                                })
                                this.pointFormLabel = [...list]
                            }
                            this.pointTitle = res.data.title.params
                        }else{
                            this.pointFormLabel = []
                        } 

                        PointQueryPoint(_data).then(res1=>{
                            if(res1.isSuccess && res1.data){
                                this.pointNameList = res1.data || []
                                if(res1.data.length > 0){
                                    this.pointForm.pointName = res1.data[0].pointName
                                    this.pointForm.CODE_ID = res1.data[0].codE_ID
                                    GetFormulaByModeId(res1.data[0].instrumentModelID).then(res2=>{
                                        if(res2.isSuccess){
                                            this.formulaList = res2.data || []
                                        }
                                    })
                                }else{
                                    this.pointForm.pointName = ''
                                }
                            }else{
                                this.pointNameList = []
                                this.pointForm.pointName = ''
                            }
                        })
                    }
                })
            }
        },
        onPointVales(){
            getPointValves({
                id:this.treeNodeId
            }).then(res=>{
                if(res.isSuccess){
                    this.pointList = res.data || []
                }else{
                    this.pointList = []
                }
            })
        },
        handleAddPoint(data){
            if(data){
                this.pointForm = {...data}
                this.pointDialogEdit = true
                this.Old_DT = data.dt
            }else{
                this.pointForm = {}
                this.pointForm = {
                    ...this.pointForm,
                    dt: DateUtils.formatDate(DateUtils.getDate('today')),
                }
                this.pointDialogEdit = false
            }
        
            this.pointListDialogVisible = true
        },
        handleCancelPoint(){
            const _d = {}
            _d.pointName = this.pointForm.pointName
            _d.dt = this.pointForm.dt
            this.pointForm = {..._d}
            this.pointDialogEdit = false
            this.pointListDialogVisible = false
        },
        handleSavePoint(){
            const _data = {}
            const params = []
            for(let key in this.pointForm){
                if(key.startsWith('Param')){
                    params.push({
                        param:key,
                        value:this.pointForm[key],
                        paramName:''
                    })
                }else{
                    _data[key] = this.pointForm[key]
                }
            }
            _data.Old_DT = this.Old_DT || ''
            _data.tp = this.pointDialogEdit ? 1 : 0
            _data.params = params
            if(!this.pointDialogEdit){
                _data.id = this.treeId
            }

            if(this.pointDialogEdit){
                PointQueryByIdEdit(_data).then(res=>{
                    if(res.isSuccess){
                        this.onPointQuery()
                        this.handleCancelPoint()
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
                
            }else{
                PointQueryByIdAdd(_data).then(res=>{
                    if(res.isSuccess){
                        this.onPointQuery()
                        this.handleCancelPoint()
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }

        },
        handleDelPointList(data){
           this.$confirm(`确认删除该条数据？删除后不可恢复，请谨慎操作！`,'提示',{
                type:'warning',
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                confirmButtonClass: 'el-button--danger',
            }).then(() => {
                PointQueryByIdDel({
                    CODE_ID:data.codE_ID,
                    DT:data.dt || ''
                }).then(res =>{
                    if(res.isSuccess){
                        this.$message.success("删除成功");
                        this.onPointQuery()
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }).catch(() => {});  
        },
        handleCancelDialogTable(){
            this.appendDatasDialogVisible = false
            this.pointDialogDataList = []
            this.dialogParams = []
        },
        handleAddPointMore(){
            if(this.treeId){
                QueryTitleByTreeID({
                    treeId:this.treeId,
                    statioN_ID:this.stationId,
                    treeStyle:this.menuSelModel,
                }).then(res =>{
                    if(res.isSuccess){
                        if(res.data && res.data.title){
                            this.appendDatasDialogVisible = true
                            for (let i = 0; i < 30; i++) {
                                let dataItem = {
                                    rowKey:i+1,
                                    pointName:'',
                                    dt:'',
                                };
                                if(res.data.params && res.data.params.length > 0){
                                    this.dialogParams = res.data.params
                                    res.data.params.forEach(item=>{
                                        dataItem[item.paramName] = ''
                                    })
                                }
                                this.pointDialogDataList.push(dataItem)
                            }
                        }else{
                            this.dialogParams = []
                            this.pointDialogDataList = []
                            this.$message.warning('当前无数据无法新增！')
                        }
                    }else{
                        this.pointDialogDataList = []
                        this.$message.error(res.errorMessage)
                    }
                })
            }else{
                this.$message.warning('请在左侧选择要设置的菜单！')
            }
        },
        handleSaveDialogTable(){
            const _list = this.pointDialogDataList
            .filter(item => {
                const val = Object.values(item);
                return val.filter((name, i) => i !== 0 && name !== '').length > 0;
            })
            .map(item => this.transformItem(item));

            const invalidItems = _list.filter(item => 
                !item.params || item.params.length === 0 ||
                item.params.some(param => !param.value && param.value !== 0)
            );
            
            if (invalidItems.length > 0) {
                this.$message.warning(`检测到${invalidItems.length}条数据参数不完整，请填写完整后再保存！`);
                return;
            }
            SetAllParamsByTreeID(_list).then(res=>{
                if(res.isSuccess){
                    this.handleCancelDialogTable()
                    this.$message.success('保存成功！')
                    this.onPointQuery()
                }else{
                    this.$message.error(res.errorMessage)
                }
            })
        },
        transformItem(item) {
            const data = {
                codE_ID: item.codE_ID,
                dt: item.dt,
                old_DT: '',
                pointName: item.pointName,
                tp: 0,
                params: this.dialogParams.map(pa => ({
                    param: pa.param,
                    paramName: pa.paramName,
                    value: item[pa.paramName] || ''
                })).filter(param => param.value !== '')
            };
            return data;
        },
        handleAddRowClick(){
            const len = this.pointDialogDataList.length
            const total = len + this.num
            const _list = [...this.pointDialogDataList]
            for (let i = len + 1; i <= total; i++) {
                const dataItem = {}
                for(let l in this.pointDialogDataList[0]){
                    if(l == 'rowKey'){
                        dataItem.rowKey = i
                    }else{
                        dataItem[l] = ''
                        
                    }
                }
                _list.push(dataItem)
            }
            this.pointDialogDataList = [..._list]
            this.addRowDialogVisible = false
        },
    }
})
</script>

<style scoped lang="scss">
 

</style>